const http = require('http')
const url = require("url");
const querystring = require('querystring');
const fs = require('fs') //引入fs功能

const server = http.createServer()
server.listen(3001)

let value = fs.readFileSync('persons.json').toString()
value = JSON.parse(value)

server.on('request', (req, res) => {

    let urlstr = req.url
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' })

    if (urlstr.startsWith('/login')) {
        urlstr = urlstr.replace('/login?', '')
        const user = querystring.parse(urlstr)

        res.end(fn(user))
    } else if (urlstr.startsWith('/register')) {
        urlstr = urlstr.replace('/register?', '')
        const user = querystring.parse(urlstr)

        res.end(fn2(user))
    } else {
        res.end('请求无效')
    }
})
// Content-Type: text/html;charset=utf8
// http://localhost:3001/login

function fn(user1) {
    let user = user1
    // 登录
    let admin = value.find(item => user.username === item.username && user.password === item.password)
    if (admin) {
        return '登录成功'

    } else {
        return '用户名或密码错误'

    }
}

function fn2(user1) {
    // let user = { username: "admin1", password: "12345" }
    // let user = {"username":"xm3","password":"333"}
    let user = user1
    // 注册
    let tag = value.find(item => item.username === user.username)
    if (tag) {
        // console.log('该用户已注册');
        return '该用户已注册'
        //  document.write('该用户已注册')
    } else {
        
        value.push(user)
        fs.writeFileSync('persons.json', JSON.stringify(value), { flag: 'w' })
        // console.log(value);
        return '注册成功'
    }
}